<template> <div class="page-container">
  <div class="toolbar">
     <el-row>
      <el-tabs type="border-card"  v-model="activeName">
       <el-tab-pane label="活动基本信息"  name="one">
         <el-form :inline="true" :model="dataForm" label-width="110px" style="text-align:center;" ref="dataForm"  :disabled="this.$route.query.disabled" class="form">
       <el-row style="margin-top: -20px;">
       <el-divider content-position="center">
        <span style="font-size:16px;font-weight:800">活动基本信息</span> 
       </el-divider>
       <el-form-item label="平台简称"  prop="platformCode">
        <el-select v-model="dataForm.platformCode" placeholder="" @change="getPlatformPoint">
           <el-option v-for="(item,index) in platform"  :label="item.name" :key="item.name":value="item.code" ></el-option>
        </el-select>
       </el-form-item>
          <el-form-item label="来源类型"  prop="sourceType" >
         <el-select v-model="dataForm.sourceType"  placeholder="请选择类型">
           <el-option label="现金划拨" value="cash"></el-option>
           <el-option label="虚拟预算划拨" value="debt"></el-option>
         </el-select>
       </el-form-item>
       <el-form-item label="活动规则名称"  prop="name" >
        <el-input v-model="dataForm.name" placeholder="请输入"></el-input>
       </el-form-item>
        <el-form-item label="活动总积分"  prop="total" >
        <el-tooltip placement="bottom" class="item" effect="light">
        <div slot="content">当前平台活动总可用积分为:{{maxTotal}}</div>
        <el-input v-model="dataForm.total" placeholder="请输入" type="number" maxlength="20"  @change="platformMaxPointcheck"></el-input>
        </el-tooltip>
       </el-form-item>
       <el-form-item label="开始日期"  prop="startTime" >
         <el-date-picker v-model="dataForm.startTime" type="datetime" placeholder="请选择开始日期"></el-date-picker>
       </el-form-item>
       <el-form-item label="结束日期"  prop="endTime" >
          <el-date-picker v-model="dataForm.endTime" type="datetime" placeholder="请选择结束日期"></el-date-picker>
       </el-form-item>
         <el-form-item label="积分模板"   prop="sceneName">
              <el-select v-model="templateForm.sceneId"  placeholder="请输入" multiple> <!-- default-first-option filterable allow-create -->
                <el-option v-for="item in searchScene"  :key="item.sceneName" :label="item.sceneName" :value="item.sceneId"></el-option>
              </el-select>
            </el-form-item>
         <el-form-item label="活动描述"  prop="description" >
        <el-input v-model="dataForm.description" type="textarea" placeholder="请输入"></el-input>
       </el-form-item>
       </el-row>
      </el-form>
         <el-button type="primary" size="small" @click="$router.go(-1)">返回</el-button>
         <el-button type="primary" size="small" @click="nextStepRulePower(1)">下一步</el-button>
     </el-tab-pane>

         <el-tab-pane label="积分场景配置" name="two" :disabled="NextDisabledtwo">
             <el-form  v-for="(templates,index) in selBySceneId" :key="index">
                <el-row style="margin-top: -20px;">
                <div style="background-color:#f0f3f4;text-align:left;padding:10px 20px;font-weight:700;margin-bottom:15px;margin-top:15px;border-bottom:1px solid #ccc;">
                <span>{{templates.sceneName}}</span>
              </div>
                <el-form :model="tempForm" v-for="(trp,i) in templates.list" :key="i" label-position="right" ref="resssss">
                   <el-form-item v-text="trp.ruleTypeName" style="float:left;padding-right:20px">{{trp.ruleTypeName}}</el-form-item>
                   <el-form-item class="b" v-html="trp.expression" v-model="tempForm.addScore">{{trp.expression}}</el-form-item>
                </el-form>
              </el-row>
             </el-form>
              <el-button type="primary" size="small" @click="nextStepRulePower(2)">上一步</el-button>
              <el-button type="primary" size="small" @click="submitForm()" v-show="!this.$route.query.disabled">保存</el-button>
         </el-tab-pane>
    </el-tabs>
   </el-row>
  </div>
 </div>
</template>
<script>
//一.导包区
import jicTable from "@/components/jicComponentGallery/jicTable";
import { mapState } from "vuex";
import ThemePicker from "@/components/ThemePicker";
import LangSelector from "@/components/LangSelector";
import VDistpicker from "v-distpicker";
import elTree from "@/views/tree/src/tree.vue";
import { param } from "../../../utils";

//二.数据输出区
export default {
  //2.1 注册组件
  components: {
    jicTable,
    ThemePicker,
    LangSelector,
    VDistpicker,
    elTree
  },

  //2.2 数据初始化区
  data() {
    return {
      //2.2.1 公共数据初始化
      searchSize: "mini",
      maxTotal:0,
      NextDisabledtwo: true,
      platformMaxPoint:null,
      activeName: "one",
      searchScene: [], //场景对象
      selBySceneId: [],
      selBySceneIdDetail: [],
      platform: [], //测试存数据
      tempForm:{},
      selectEcho:null,
      //积分模板
      templateForm: {
        id: null,
        pid: null,
        sceneId: null,
        sceneName: null,
        code: null,
        action: null,
        addType: null,
        ruleType: null,
        extraType: null,
        expression: null,
        title: null,
        addScore: null,
        increaseScore: null,
        minScore: null,
        maxScore: null,
        fullNum: null,
        dailyNum: null,
        maxNum: null,
        productType: null,
        deleteFlag: null,
        weight: null,
        ruleTypeShow: null,
        hrShow: null,
        extraBtn: null,
        description: null,
        applierId: null,
        applyReason: null,
        auditorId: null,
        auditReason: null,
        createTime: null,
        updateTime: null,
        creator: null,
        creatorName: null,
        updater: null,
        updaterName: null,
        auditSts: null,
        templateId: null,
        currentAction: null
      },
      //设置活动规则基本信息
      dataForm: {
        id: null,
        deptId: null,
        bdCode: null,
        platformCode: null,
        name: null,
        code: null,
        outRuleKey: null,
        outActivityRuleKey: null,
        description: null,
        limited: null,
        available: null,
        cost: null,
        total: null,
        frozen: null,
        unplanRelease: null,
        overtimeRelease: null,
        invalidRelease: null,
        startTime: null,
        endTime: null,
        applierId: null,
        applyReason: null,
        applyTime: null,
        auditorId: null,
        auditReason: null,
        auditTime: null,
        delayApplierId: null,
        delayApplierReason: null,
        delayAuditorId: null,
        delayAuditReason: null,
        detail: null,
        sourceType: null,
        sts: null,
        createTime: null,
        updateTime: null,
        creator: null,
        updater: null,
        deleteFlag: null
      },
      //设置活动规则配置
      dataForm1: {
        id: null,
        pid: null,
        appKey: null,
        ruleKey: null,
        type: null,
        code: null,
        name: null,
        valueType: null,
        minValue: null,
        maxValue: null,
        description: null,
        applierId: null,
        applierReason: null,
        auditorId: null,
        auditReason: null,
        creatorName: null,
        upArName: null,
        sts: null,
        templateId: null,
        action: null,
        caculateType: null,
        ruleType: null,
        extraType: null,
        expression: null,
        fullNum: null,
        dailyNum: null,
        maxNum: null,
        productType: null,
        startTime: null,
        endTime: null
      },
      dataForm2: {},
      rulePowerForm: {
        consumeIntegralNum: null,
        ruleType: 1,
        orderConsume: null,
        deptName: null,
        mememberIntegraIncrement: [{ consumeNum: "", giveIntegralNum: "" }],
        consumeFlag: null,
        orderFlag: null,
        flag: null,
        share: null,
        consumeNum: null,
        phasedConsumeNum: null,
        ruleName: null,
        ruleNum: null,
        giveIntegralNum: null,
        giveIntegralMaxNum: null,
        consumeMode: null,
        obtainMode: null,
        giveGrowthMaxNum: null,
        notPictureGiveGrowthNum: null,
        havePictureMaxNum: null,
        havePictureGiveGrowthNum: null,
        giveGrowthNum: null,
        obtainModeName: null,
        exchangeType: 1
      },
      //trigger 为blur 表示丢失焦点;为change 表示值发生变化;
      dataFormRules: {
        /*  id:[
   { required: true, message: "请输入主键", trigger: "blur" },
   { min: 3, max: 5, message: "长度在 0 到 20 个字符", trigger: "blur" },
   ], */
        deptId: [
          { required: true, message: "请输入部门编码", trigger: "blur" },
          { min: 0, max: 20, message: "长度在 0 到 20 个字符", trigger: "blur" }
        ],
        bdCode: [
          { required: true, message: "请输入BD部门编码", trigger: "blur" },
          { min: 0, max: 50, message: "长度在 0 到 50 个字符", trigger: "blur" }
        ],
        platformCode: [
          { required: true, message: "请输入平台ID", trigger: "blur" },
          { min: 0, max: 20, message: "长度在 0 到 20 个数字", trigger: "blur" }
        ],
        name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 0,
            max: 100,
            message: "长度在 0 到 100 个字符",
            trigger: "blur"
          }
        ],
        code: [
          { required: true, message: "请输入活动编码", trigger: "blur" },
          { min: 0, max: 50, message: "长度在 0 到 50 个字符", trigger: "blur" }
        ],
        outRuleKey: [
          { required: true, message: "请输入对外规则码", trigger: "blur" },
          { min: 0, max: 32, message: "长度在 0 到 32 个字符", trigger: "blur" }
        ],
        description: [
          { required: true, message: "请输入活动描述", trigger: "blur" },
          {
            min: 0,
            max: 255,
            message: "长度在 0 到 255 个字符",
            trigger: "blur"
          }
        ],
        limited: [
          { required: true, message: "请输入活动额度积分", trigger: "blur" }
        ],
        cost: [
          { required: true, message: "请输入活动已用积分", trigger: "blur" }
        ],
        overtimeRelease: [
          { required: true, message: "请输入活动过期释放积分", trigger: "blur" }
        ],
        invalidRelease: [
          { required: true, message: "请输入活动失效释放积分", trigger: "blur" }
        ],
        available: [
          { required: true, message: "请输入活动剩余积分", trigger: "blur" }
        ],
        /*   left:[
   { required: true, message: "请输入活动剩余积分", trigger: "blur" },
   { min: 3, max: 5, message: "长度在 0 到 20 个字符", trigger: "blur" },
   ], */
        total: [
          { required: true, message: "请输入活动总积分", trigger: "blur" }
        ],
        frozen: [
          { required: true, message: "请输入活动冻结积分", trigger: "blur" }
        ],
        unplanRelease: [
          { required: true, message: "请输入未计划释放积分", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "请输入开始日期", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "请输入结束日期", trigger: "blur" }
        ],
        applierId: [
          { required: true, message: "请输入申请人ID", trigger: "blur" },
          { min: 0, max: 20, message: "长度在 0 到 20 个字符", trigger: "blur" }
        ],
        applyReason: [
          { required: true, message: "请输入申请原因", trigger: "blur" },
          {
            min: 0,
            max: 255,
            message: "长度在 0 到 20 个字符",
            trigger: "blur"
          }
        ],
        detail: [
          { required: true, message: "请输入详情", trigger: "blur" },
          {
            min: 0,
            max: 255,
            message: "长度在 0 到 255 个字符",
            trigger: "blur"
          }
        ],
        source_type: [
          { required: true, message: "请输入来源类型", trigger: "blur" },
          {
            min: 0,
            max: 255,
            message: "长度在 0 到 255 个字符",
            trigger: "blur"
          }
        ],
        sts: [{ required: true, message: "请选择状态", trigger: "blur" }]
        /*createTime:[
   { required: true, message: "请输入创建时间", trigger: "blur" },
   { min: 3, max: 5, message: "长度在 0 到 20 个字符", trigger: "blur" },
   ],
   updateTime:[
   { required: true, message: "请输入更新时间", trigger: "blur" },
   { min: 3, max: 5, message: "长度在 0 到 20 个字符", trigger: "blur" },
   ],
   creator:[
   { required: true, message: "请输入创建用户", trigger: "blur" },
   { min: 3, max: 5, message: "长度在 0 到 20 个字符", trigger: "blur" },
   ],
   updater:[
   { required: true, message: "请输入更新用户", trigger: "blur" },
   { min: 3, max: 5, message: "长度在 0 到 20 个字符", trigger: "blur" },
   ],
   deleteFlag:[
   { required: true, message: "请输入是否删除：0不删除， 1删除 ", trigger: "blur" },
   { min: 3, max: 5, message: "长度在 0 到 20 个字符", trigger: "blur" },
   ], */
      }
    }; 
  }, 
  //2.3 Vue 方法区
  methods: {
    //2.3.1 公共方法区

    //查看场景是否存在
    getScene() {
      // 查询数据库中的场景
      let this_ = this;
      /*   if (num == 1) { */
      let params = {};
      this.utils.request.getConfActivityRuleDetailTemplateScene(
        params,
        function(res) {
          if (res.code === "0000") {
            this_.searchScene = res.data;
          } else {
            this_.$message({
              message: "操作失败, " + res.msg,
              type: "error"
            });
          }
        }
      );
    },
    selectMultiple(number){
      if(number=="1"){
        this.selectEcho = this.templateForm.sceneId;
      }else{
        this.templateForm.sceneId = this.selectEcho;
      }
    },
    //设置最大值
    getPlatformPoint(value) {
      let this_ = this;
      //通过平台查询平台积分
      let choosenItem = this.platform.filter(item => item.code === value)[0];
      //this.dataForm.total = choosenItem.available;
      //通过用户平台id查看关联信息
      let params =  {};
      params.code = choosenItem.code;
      this.utils.request.getPlatfromRela(params, function(res){
        if (res.code === "0000") {
          if(res.data.length<1) {
            this_.dataForm.platformCode= null;
            this_.$message({
            message: "当前平台没有绑定唯一结算关系!",
            type: "error"
          });
          }else{
          this_.maxTotal = choosenItem.available;
          this_.platformMaxPoint = choosenItem.available;
          this_.dataForm.bdCode = res.data[0].bdCode;
          }
        } else {
          this_.$message({
            message: "操作失败, " + res.msg,
            type: "error"
          });
        }
      });
     
    },
    platformMaxPointcheck(){
      let this_= this;
     this.dataForm.total= this_.dataForm.total>this_.platformMaxPoint?this_.platformMaxPoint:this_.dataForm.total;

    },
    //2.请求列表数据
    getDetail() {
      let this_ = this;
      if (
        this.$route.query != null &&
        this.$route.query.id != null &&
        this.$route.query.id != "" &&
        this.$route.query.id != "null" &&
        this.$route.query.id != "undefined"
      ) {
        let params = {};
        params.id = this.$route.query.id;
        if (this.$route.query.activeName == "second") {
          this.utils.request.getConfActivityRuleApplyDetail(params, function(
            res
          ) {
            if (res.code === "0000") {
              this_.dataForm = res.data;
            } else {
              this_.$message({
                message: "操作失败, " + data.msg,
                type: "error"
              });
            }
          });
        } else {
          this.utils.request.getConfActivityRuleDetail(params, function(res) {
            if (res.code === "0000") {
              this_.dataForm = res.data;
            } else {
              this_.$message({
                message: "操作失败, " + data.msg,
                type: "error"
              });
            }
          });
        }
      }else{
        this.getNowTime();
      }
    },
    getNowTime() {//自动设置时间
      var now = new Date();
      var year = now.getFullYear(); //得到年份
      var month = now.getMonth(); //得到月份
      var date = now.getDate(); //得到日期
      var hour = now.getHours(); //得到日期
      var minute = now.getMinutes(); //得到日期
      var second = now.getSeconds(); //得到日期
      month = month + 1;
      month = month.toString().padStart(2, "0");
      date = date.toString().padStart(2, "0");
      var endYear = year + 10;
      var endTime = endYear+"-"+month+"-"+date+" "+hour.toString().padStart(2, "0")+":"+minute.toString().padStart(2, "0")+":"+second.toString().padStart(2, "0");
      var startTime = year +"-"+month+"-"+date+" "+hour.toString().padStart(2, "0")+":"+minute.toString().padStart(2, "0")+":"+second.toString().padStart(2, "0");
      let this_= this;
      this_.dataForm.startTime = startTime;
      this_.dataForm.endTime = endTime;
    },
    putDetail(this_){
      let c = 0;
     let p = this_.selBySceneIdDetail;
      for(let i=0;i< p.length;i++){ //3
          let pp =  p[i].list; 
         console.log(p[i]);
        for(let j=0;j<pp.length;j++){//2 3 1
           console.log(pp[j])
          let ll = (pp[j].expression.split("<input").length)-1; //1
          let aList =  window.document.getElementsByClassName("a")
          for (let k = 0; k < ll; k++) {
            if(pp[j].addType=="1"){
              k==1?(pp[j].maxScore=aList[c].value):(pp[j].minScore=aList[c].value)
            }
            if(pp[j].addType=="2"){
               pp[j].addScore=aList[c].value;
            }
            if(pp[j].addType=="4"){
               k==1?(pp[j].increaseScore=aList[c].value):(pp[j].dailyNum=aList[c].value)
            }
            if(pp[j].addType=="5"){
               k==1?(pp[j].addScore=aList[c].value):(pp[j].fullNum=aList[c].value)
            }
            c++
          }
        }
      }
    },
    submitForm: function() {
      let this_ = this;
      let bList = window.document.getElementsByClassName("b")
      this.putDetail(this_);
      this_.$refs.dataForm.validate(valid => {
        if (valid) {
          this_.$confirm("确认提交吗？", "提示", {}).then(() => {
            this_.editLoading = true;
            let params = {};
             params.dataForm =this.dataForm;
             params.dataForm1=this.dataForm1;
             params.dataForm2=this.selBySceneIdDetail;
            //
            if(this.$route.query.action == "insert"){
            this_.utils.request.saveConfActivityRuleApply(params, function(res) {
              if (res.code === "0000") {
                this_.$message({ message: "操作成功", type: "success" });
              } else {
                this_.$message({ message: "操作失败", type: "error" });
              }
            });
            }else if(this.$route.query.action == "update"){
          this_.utils.request.saveConfActivityRule(params, function(res) {
              if (res.code === "0000") {
                this_.$message({ message: "操作成功", type: "success" });
              } else {
                this_.$message({ message: "操作失败", type: "error" });
              }
            });
            }
            this_.$router.go(-1);
          });
        }
      });
    }, //下一步调整
    nextStepRulePower: function(num) {
      let this_ = this;
      //规则配置下一步
      if (num == "1") {
          this.selectMultiple("1");
        this_.$refs.dataForm.validate(valid => {
          if (valid) {
            this.templateForm.sceneId = String(this.templateForm.sceneId);
            if (String(this.templateForm.sceneId).length > 0) {
              let params = this.templateForm;
              this_.utils.request.findConfActivityRuleDetailTemplateBySceneIdTemplate(params,function(res) {
                  if (res.code === "0000") {
                    this_.selBySceneId = res.data;
                    this_.selBySceneIdDetail = res.data;
                    this_.NextDisabledtwo = false;
                    this_.activeName = "two";
                    console.log(this_.selBySceneId);
                  } else {
                    this_.$message({ message: "操作失败", type: "error" });
                  }
                }
              );
            }
          }
        });
      }
      //积分配置上一步
      if (num == "2") {
          this.selectMultiple("2");
        this.activeName = "one";
      }
    },
    // 7.页面弹窗处理方法
    add() {
      this.dialogVisible = true;
    },

    // 8.关闭弹窗
    handleClose() {
      this.dialogVisible = false;
    },

    /*图片预览*/
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /*图片移除*/
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    back() {
      this.$router.go(-1);
    },
    /**查询子平台列表 */
    getPlatform() {
      let this_ = this;
      this_.utils.request.getPlatformName(null, function(res) {
        if (res.code === "0000") {
          debugger
          this_.platform = res.data;
        } else {
          this_.$message({ message: "操作失败", type: "error" });
        }
      });
    }
    //==========2.3.1 JavaScript 自定义方法区==========
  },
  //1.初始化页面调用方法(dom元素绑定后再执行初始化数据操作)
  mounted() {
    this.getDetail();
    this.getScene();
    this.getPlatform(); //查询子平台
  }
};
</script>
<style lang="scss" scoped>
/* ele组件样式重置 */
.common-content {
  padding: 10px;
  box-sizing: border-box;

  .search-wrap /deep/ {
    .el-form-item__label {
      height: 32px;
      line-height: 32px;
    }

    .el-form-item__content {
      height: 32px;
      line-height: 32px;
      width: 150px;
    }

    .el-input--mini .el-input__inner {
      height: 32px;
      line-height: 32px;
    }

    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
      width: 150px;
    }
  }

  /* 多日期样式重置 */
  .el-dater /deep/ .el-form-item__content {
    width: 330px;
  }

  /* 通用工具部分样式 */
  .tool-wrap {
    width: 100%;
    height: auto;
    position: relative;
    overflow: hidden;

    .left-area {
      float: left;
      width: 80%;
      text-align: left;

      button {
        margin-right: 15px;
        border-radius: 5px;
      }
    }

    .right-area {
      float: right;
      width: 50%;
      text-align: right;
    }
  }

  /* 表格部分样式 */
  .table-wrap {
    width: 100%;
    max-height: 600px;
    margin-top: 20px;
  }

  /* 弹窗样式 */
  .dialog-wrap /deep/ .el-dialog__footer {
    text-align: center !important;
  }
}
</style>
